package com.coocaa.x.service.litedaemon.daemons.tvpie.app;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.IBinder;
import android.os.RemoteException;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.data.JString;
import com.coocaa.x.framework.utils.AsyncTask;
import com.coocaa.x.framework.utils.Cache;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.liteccconnector.aidl.ILiteCCConnectorHandler;
import com.coocaa.x.service.litedaemon.DETargetBean;
import com.coocaa.x.service.litedaemon.LiteDaemon;
import com.coocaa.x.service.litedaemon.daemons.tvpie.app.bean.AppBean;
import com.coocaa.x.service.litedaemon.daemons.tvpie.app.bean.AppMessage;
import com.coocaa.x.service.litedaemon.daemons.tvpie.app.bean.AppResultBean;
import com.coocaa.x.service.litedaemon.daemons.tvpie.app.bean.DownloadSkyApp;
import com.coocaa.x.service.litedaemon.daemons.tvpie.app.bean.StartDownloadSkyApp;
import com.coocaa.x.service.litedaemon.daemons.tvpie.app.bean.VersionBean;
import com.coocaa.x.service.litedaemon.daemons.tvpie.app.def.CoocaaDEExtentionDefine;
import com.coocaa.x.service.litedaemon.daemons.tvpie.app.util.InstalledFilter;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderServiceListener;
import com.coocaa.x.service.litedownloader.data.DownloadError;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.ProcessInfo;
import com.coocaa.x.service.litedownloader.data.TaskInfo;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.aidl.ILitePMUninstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.skyworth.deservice.DEDefine;
import com.skyworth.deservice.api.def.SRTDEServicesCmdDef;
import com.skyworth.deservice.api.def.SRTDEServicesCmdDef.SkyDEServiceChannelEnum;
import com.skyworth.framework.skysdk.properties.SkyGeneralProperties;
import com.skyworth.webSDK.webservice.tcappstore.AppDetailData;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreUpdateBean;
import com.tianci.de.api.DEChannelSession;
import com.tianci.de.api.JsonParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by dvlee1 on 6/24/15.
 */
public class TVPieAppDaemon extends LiteDaemon {

    public static final String TAG = "skyde";
    public static final int VERSIONCODE = 4;
    private static final String APP_SESSION = "tianci_appstore";

    private static final int SEND_APP_COUNT = 30;

    private interface CoocaaCmdHandler {
        byte[] onHandle(DETargetBean bean, String cmd, String json);
    }

    private HashMap<String, CoocaaCmdHandler> mCmdHandlerMap = new HashMap<String, CoocaaCmdHandler>();

    private static LiteDaemonInfo info = null;

    private Cache<String, AppMessage> downloadSkyAppCache = new Cache<String, AppMessage>();
    private Cache<String, DownloadTask> taskCache = new Cache<String, DownloadTask>();
    private Cache<String, AppStoreUpdateBean> updateBeanCache = new Cache<String, AppStoreUpdateBean>();

    static {
        info = new LiteDaemonInfo();
        info.id = "com.coocaa.tvpie.app";
        info.name = "电视派应用";
    }

    public TVPieAppDaemon() {
        super(info);
    }

    @Override
    protected void onCreate(Context context) {
        try {
            initCmdHandler();
            XServiceManager.getLiteCCConnectorService().addHandler(ccconnectorHandler);
            XServiceManager.getDownloaderService().setListener(downloaderStub);
            XServiceManager.getLitePMService().addInstallListener(installListener);
            XServiceManager.getLitePMService().addUninstallListener(uninstallListener);

            // TODO what?
            // XServiceManager.getLitePMService().setSpeedUpListener(speedUpListener);
            // load default can update apps
            // TODO get list
            List<AppStoreUpdateBean> list = new ArrayList<AppStoreUpdateBean>();
            for (AppStoreUpdateBean bean : list)
                updateBeanCache.add(bean.packagename, bean);

            List<DownloadTask> tasks = XServiceManager.getDownloaderService()
                    .getTaskList();
            for (DownloadTask task : tasks)
                taskCache.add(task.ID, task);
            LogUtils.i(TAG, "taskCache.size()=" + taskCache.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private IDownloaderServiceListener.Stub downloaderStub = new IDownloaderServiceListener.Stub() {
        private void send2Mobile(final DownloadTask task, final String cmd) {
            runOnThread(new Runnable() {
                @Override
                public void run() {
                    AppResultBean<AppResultBean.DownTask> msg = new AppResultBean<AppResultBean.DownTask>();
                    if (!taskCache.containsKey(task.ID))
                        taskCache.add(task.ID, task);

                    AppResultBean.DownTask mDownTask = new AppResultBean.DownTask(task);
                    LogUtils.i("wl", "cmd:" + cmd + ";apkPath=" + mDownTask.apkPath);
                    msg.result = mDownTask;
                    notifyToMobile(null, cmd, msg.toString());
                }
            });
        }

        @Override
        public void onReady(final DownloadTask task) throws RemoteException {
            send2Mobile(task,
                    SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_DOWNLOAD_ONREADY
                            .toString());
        }

        @Override
        public void onPrepare(DownloadTask task) throws RemoteException {
            send2Mobile(
                    task,
                    SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_DOWNLOAD_ONPREPARE
                            .toString());
        }

        @Override
        public void onStart(final DownloadTask task) throws RemoteException {
            send2Mobile(
                    task,
                    SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_DOWNLOAD_ONSTART
                            .toString());
        }

        @Override
        public void onStop(DownloadTask task) throws RemoteException {
            send2Mobile(
                    task,
                    SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_DOWNLOAD_ONSTOP
                            .toString());
        }

        private Timer timer = null;
        private Cache<String, AppResultBean<AppResultBean.OnProcessInfo>> onProcessInfoMessage = new Cache<String, AppResultBean<AppResultBean.OnProcessInfo>>();

        @Override
        public void onProcessInfo(DownloadTask task, ProcessInfo info)
                throws RemoteException {
            synchronized (this) {
                if (timer == null) {
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {

                            synchronized (TVPieAppDaemon.this) {
                                if (onProcessInfoMessage.size() > 0) {
                                    // TODO test
                                    runOnThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            List<AppResultBean<AppResultBean.OnProcessInfo>> msgs = onProcessInfoMessage
                                                    .values();
                                            onProcessInfoMessage.clear();
                                            for (AppResultBean<AppResultBean.OnProcessInfo> msg : msgs) {
                                                notifyToMobile(null, SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_DOWNLOAD_ONPROCESS
                                                                .toString(),
                                                        msg.toString());
                                            }
                                        }
                                    });

                                } else {
                                    timer.cancel();
                                    timer = null;
                                }
                            }
                        }
                    }, 0, 3000);
                }
                AppResultBean<AppResultBean.OnProcessInfo> msg = new AppResultBean<AppResultBean.OnProcessInfo>();
                AppResultBean.OnProcessInfo bean = new AppResultBean.OnProcessInfo(task, info);
                msg.result = bean;
                onProcessInfoMessage.add(task.ID, msg);
            }
        }


        @Override
        public void onFinish(final DownloadTask task) throws RemoteException {

            runOnThread(new Runnable() {
                @Override
                public void run() {
                    if (!taskCache.containsKey(task.ID))
                        taskCache.add(task.ID, task);

                    send2Mobile(
                            task,
                            SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_DOWNLOAD_ONFINISH
                                    .toString());
                }
            });
        }

        @Override
        public void onError(DownloadTask task, DownloadError error)
                throws RemoteException {

            AppResultBean<AppResultBean.onError> msg = new AppResultBean<AppResultBean.onError>();
            msg.result = new AppResultBean.onError(task, error);
            notifyToMobile(null, SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_DOWNLOAD_ONERROR
                    .toString(), msg.toString());
        }

        @Override
        public void onDelete(DownloadTask task) throws RemoteException {

            send2Mobile(
                    task,
                    SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_DOWNLOAD_ONDELETE
                            .toString());
        }
    };

    @Override
    protected void onDestroy() {
        try {
            XServiceManager.getLiteCCConnectorService().removeHandler(ccconnectorHandler);
            XServiceManager.getLitePMService().removeInstallListener(installListener);
            XServiceManager.getLitePMService().removeUninstallListener(uninstallListener);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void initCmdHandler() {
        LogUtils.i(TAG, "initCmdHandler()");
        /**
         * 获取版本号
         */
        mCmdHandlerMap.put("SKY_COMMAND_APPSTORE_MOBILE_GET_VERSION",
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        AppResultBean<VersionBean> bean = new AppResultBean<VersionBean>(json);
                        VersionBean mGetVersion = new VersionBean();
                        mGetVersion.versionCode = VERSIONCODE;
                        bean.result = mGetVersion;
                        responseToMobile(deBean, cmd, bean.toString());
                        return null;
                    }
                });


        /**
         * 启动应用
         */
        mCmdHandlerMap
                .put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_START_APP
                        .toString(), new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, final String json) {
                        LogUtils.d("skydeex", "222SKY_COMMAND_APPSTORE_MOBILE_START_APP  json:" + json);
                        AppMessage msg = AppMessage.parseJObject(json, AppMessage.class);
                        AppResultBean.StartApp app = AppResultBean.parseObject(msg.params, AppResultBean.StartApp.class);
                        AppResultBean<AppResultBean.StartApp> result = new AppResultBean<AppResultBean.StartApp>(json);
                        result.result = app;

                        try {
                            XServiceManager.getLitePMService().startAppByComponentName(mContext.getClass().getName(), false, new
                                    ComponentName(app.pkgname, app.mainActivity));
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        responseToMobile(deBean, cmd, result.toString());
                        return null;
                    }
                });

        /**
         * 获取已安装应用列表
         */
        mCmdHandlerMap
                .put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_GET_INSTALLED_APPS
                        .toString(), new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {

                        SkyGeneralProperties.getProperty("x_launcher_entry");


                        AppResultBean<List<AppResultBean.GetInstalled>> msg = new AppResultBean<List<AppResultBean.GetInstalled>>(json);
                        List<AppInfo> l = null;

                        try {
                            l = XServiceManager.getLitePMService().getInstalledApps();

                        } catch (RemoteException e) {

                            e.printStackTrace();
                        } catch (Exception e) {

                            e.printStackTrace();
                        }
                        if (l == null) {
                            l = new ArrayList<AppInfo>();
                        }

                        ArrayList<AppResultBean.GetInstalled> ll = InstalledFilter.getInstalledApp(l);
                        msg.result = ll;

//						    if(ll.size()>50){
//						    	ArrayList<GetInstalled> ll1=new ArrayList<AppResultBean.GetInstalled>();
//						        ll1=(ArrayList<GetInstalled>) ll.subList(0, 50);
//						    }


                        for (int i = 0; i <= ll.size() / SEND_APP_COUNT; i++) {
                            List<AppResultBean.GetInstalled> resultList = new ArrayList<AppResultBean.GetInstalled>();
                            resultList = ll.subList(i * SEND_APP_COUNT, (i + 1) * SEND_APP_COUNT > (ll.size()) ? (ll.size
                                    ()) : (i + 1) * SEND_APP_COUNT);
                            msg.result = resultList;
                            msg.total = "" + ll.size();
                            msg.page = "" + (i + 1);

                            responseToMobile(deBean, cmd, msg.toString());
                        }

                        // 返回下载暂停信息
                        for (DownloadTask task : taskCache.values()) {
                            LogUtils.i("skyde", task.title);
                            if (task.info == null) continue;
                            if (task.info.state == TaskInfo.TASK_STATE.STOPED) {
                                try {
                                    downloaderStub.onStop(task);
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                                LogUtils.i("skyde", task.title + " stoped");
                            }
                        }
                        return null;
                    }
                });


        /**
         * 下载应用
         */
        mCmdHandlerMap
                .put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_DOWNLOAD_SKYAPP
                        .toString(), new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        AppMessage msg = AppMessage.parseJObject(json,
                                AppMessage.class);
                        DownloadSkyApp str = DownloadSkyApp.parseJObject(msg.params,
                                DownloadSkyApp.class);
                        String download_url = null;
                        download_url = getDownurl(str.appid, "");
                        if (download_url == null)
                            download_url = "";
                        AppDetailData appDetail = null;
                        int tryCount = 0;
                        while (appDetail == null && tryCount <= 5) {
                            appDetail = getAppDetail(str.appid, "");
                            tryCount++;
                        }
//							String download_path = AppDataProvider
//									.getInstance().getDownloadPath();
                        try {
                            DownloadTask task = new DownloadTask(
                                    appDetail.id);
                            task.title = appDetail.title;
                            task.url = download_url;
//								task.savepath = download_path;
                            task.filename = System.currentTimeMillis()
                                    + ".apk";
                            task.extra = new DownloadExtra(appDetail.id,
                                    appDetail.packageName,
                                    appDetail.iconUrl, appDetail.title)
                                    .toString();
                            XServiceManager.getDownloaderService().add(task);
                            XServiceManager.getDownloaderService().start(task);
                            downloadSkyAppCache.add(task.ID, msg);
                            taskCache.add(str.appid, task);
                        } catch (Exception e) {
                            LogUtils.e(TAG, "error from download cmd");
                            e.printStackTrace();
                        }
                        return null;
                    }
                });

        /**
         * 暂停下载
         */
        mCmdHandlerMap
                .put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_PAUSEDOWNLOAD_SKYAPP
                        .toString(), new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        AppMessage msg = AppMessage.parseJObject(json,
                                AppMessage.class);
                        StartDownloadSkyApp str = JString.parseJObject(msg.params,
                                StartDownloadSkyApp.class);
                        DownloadTask task = taskCache.get(str.appid);
                        try {
                            if (task != null) {
                                XServiceManager.getDownloaderService().stop(task);
                            }
                        } catch (RemoteException e) {

                            e.printStackTrace();
                        }
                        return null;
                    }
                });

        /**
         * 恢复下载
         */
        mCmdHandlerMap
                .put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_STARTDOWNLOAD_SKYAPP
                        .toString(), new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        AppMessage msg = AppMessage.parseJObject(json,
                                AppMessage.class);
                        StartDownloadSkyApp str = StartDownloadSkyApp.parseJObject(msg.params, StartDownloadSkyApp.class);
                        DownloadTask task = taskCache.get(str.appid);
                        try {
                            if (task != null) {
                                XServiceManager.getDownloaderService().start(task);
                            }
                        } catch (RemoteException e) {

                            e.printStackTrace();
                        }
                        return null;
                    }
                });

        /**
         * 取消下载
         */
        mCmdHandlerMap.put(
                "SKY_COMMAND_APPSTORE_MOBILE_CANCELDOWNLOAD_SKYAPP"
                , new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        AppMessage msg = AppMessage.parseJObject(json,
                                AppMessage.class);
                        StartDownloadSkyApp str = StartDownloadSkyApp.parseJObject(msg.params, StartDownloadSkyApp.class);
                        DownloadTask task = taskCache.get(str.appid);
                        try {
                            if (task != null) {
                                XServiceManager.getDownloaderService().delete(task);
                            }
                        } catch (RemoteException e) {

                            e.printStackTrace();
                        }
                        return null;
                    }
                });

        /**
         * 卸载应用
         */
        mCmdHandlerMap.put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_UNINSTALL_APP.toString(),
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        LogUtils.i("dvlee", "uninstall " + json);
                        AppMessage msg = AppMessage.parseJObject(json,
                                AppMessage.class);
                        AppBean params = AppBean.parseJObject(msg.params,
                                AppBean.class);
                        try {
                            XServiceManager.getLitePMService().uninstall(params.pkgname, false);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                });

        mCmdHandlerMap
                .put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_GET_APKINFO
                        .toString(), new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        AppMessage msg = AppMessage.parseJObject(json,
                                AppMessage.class);

                        AppMessage.ApkInfoBean str = AppMessage.ApkInfoBean.parseJObject(msg.params,
                                AppMessage.ApkInfoBean.class);
                        AppMessage.MobileApkInfo apkinfo = new AppMessage.MobileApkInfo();
                        DownloadTask task = taskCache.get(str.appid);
                        if (task != null) {
                            try {
                                task = XServiceManager.getDownloaderService().refresh(task);
                                switch (task.info.state) {
                                    case FINISH: {
                                        apkinfo.name = task.title;
                                        apkinfo.path = task.savepath + "/"
                                                + task.filename;
                                        break;
                                    }
                                    default:
                                        break;
                                }
                            } catch (RemoteException e) {

                                e.printStackTrace();
                            }
                        }

                        AppResultBean<AppMessage.MobileApkInfo> bean = new AppResultBean<AppMessage.MobileApkInfo>();
                        bean.result = apkinfo;

                        notifyToMobile(deBean, cmd, bean.toJSONString());
                        return null;
                    }
                });


        /**
         * 获取应用状态
         */
        mCmdHandlerMap
                .put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_GET_APPSTATUS
                        .toString(), new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        AppMessage msg = AppMessage.parseJObject(json,
                                AppMessage.class);

                        List<AppResultBean.GetAppStatus> list = AppResultBean.parseArray(msg.params, AppResultBean.GetAppStatus.class);

                        List<AppMessage.MobileAppStatus> result = new ArrayList<AppMessage.MobileAppStatus>();
                        for (AppResultBean.GetAppStatus g : list) {
                            String pkgname = g.pkgName;
                            boolean isInstalled = false;
                            boolean canUpdate = false;
                            int download_state = 0;
                            AppMessage.MobileAppStatus r = new AppMessage.MobileAppStatus();
                            try {
                                isInstalled = XServiceManager.getLitePMService().isInstalled
                                        (pkgname);
                                canUpdate = false;
                                List<AppStoreUpdateBean> beans = updateBeanCache
                                        .values();
                                for (AppStoreUpdateBean bean : beans) {
                                    if (bean.packagename
                                            .equals(pkgname)) {
                                        canUpdate = true;
                                        break;
                                    }
                                }
                                List<DownloadTask> tasks = XServiceManager
                                        .getDownloaderService()
                                        .getTaskList();
                                for (DownloadTask task : tasks) {
                                    DownloadExtra extra = DownloadExtra
                                            .parseJObject(task.extra,
                                                    DownloadExtra.class);
                                    if (extra.pkgname.equals(pkgname)) {
                                        switch (task.info.state) {
                                            case READY:
                                                download_state = AppMessage.MobileAppStatus.DOWNLOAD_READY_MASK;
                                                break;
                                            case PROCESSING:
                                                download_state = AppMessage.MobileAppStatus.DOWNLOAD_PROCESS_MASK;
                                                float current = task.info.current;
                                                float length = task.info.length;
                                                r.progrss = Math.max(0, Math.min(100, (int) ((current / length) * 100)));
                                                LogUtils.i("wl", "DOWNLOAD_PROCESS_MASK=" + r.progrss);

                                                break;
                                            case STOPED:
                                                download_state = AppMessage.MobileAppStatus.DOWNLOAD_STOP_MASK;
                                                current = task.info.current;
                                                length = task.info.length;
                                                r.progrss = Math.max(0, Math.min(100, (int) ((current / length) * 100)));
                                                LogUtils.i("wl", "DOWNLOAD_STOP_MASK=" + r.progrss);
                                                break;
                                            case FINISH:
                                                download_state = AppMessage.MobileAppStatus.DOWNLOAD_FINISH_MASK;
                                                r.appinfo.appName = extra.title;
                                                r.appinfo.pkgName = extra.pkgname;
                                                r.appinfo.apkPath = task.savepath + task.filename;
                                                break;
                                            default:
                                                break;
                                        }
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            try {
                                AppInfo info = XServiceManager
                                        .getLitePMService()
                                        .getAppInfo(pkgname);
                                if (info != null) {
                                    r.appinfo.appName = info.appName;
                                    r.appinfo.pkgName = info.pkgName;
                                    // TODO
                                    //r.appinfo.flag=info.flag;
                                    r.appinfo.apkPath = info.apkPath;
                                    r.appinfo.mainActivity = info.mainActivity;
                                }
                            } catch (RemoteException e) {

                                e.printStackTrace();
                            }

                            if (isInstalled)
                                r.status |= AppMessage.MobileAppStatus.HAS_INSTALLED_MASK;
                            if (canUpdate)
                                r.status |= AppMessage.MobileAppStatus.CAN_UPDATE_MASK;
                            r.status |= download_state;
                            result.add(r);
                        }


                        AppResultBean<List<AppMessage.MobileAppStatus>> bean = new AppResultBean<List<AppMessage.MobileAppStatus>>();
                        bean.id = msg.id;
                        bean.result = result;

                        responseToMobile(deBean, cmd, bean.toString());
                        return null;
                    }
                });

        /** 安装应用 **/
        mCmdHandlerMap
                .put(SRTDEServicesCmdDef.SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_INSTALL_APP
                        .toString(), new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {
                        AppMessage msg = AppMessage.parseJObject(json,
                                AppMessage.class);
                        AppMessage.MobileApkInfo params = AppMessage.MobileApkInfo.parseJObject(
                                msg.params, AppMessage.MobileApkInfo.class);
                        try {
                            // TODO isroot?
                            InstallParams _params = new InstallParams();
                            _params.setFrom(InstallParams.INSTALL_FROM.COOCAA_MARKET);
                            XServiceManager.getLitePMService().install(params.path, false, _params);
                        } catch (RemoteException e) {

                            e.printStackTrace();
                        }
                        return null;
                    }
                });


        /**
         * 获取已下载应用
         */
        mCmdHandlerMap.put("SKY_COMMAND_APPSTORE_MOBILE_GET_DOWNLOADED_SKYAPPS",
                new CoocaaCmdHandler() {
                    @Override
                    public byte[] onHandle(DETargetBean deBean, String cmd, String json) {

                        try {
                            List<DownloadTask> tasks = XServiceManager
                                    .getDownloaderService()
                                    .getTaskList();


                            if (tasks == null) {
                                return null;
                            }
                            List<AppResultBean.GetDownLoaded> downLoaders = new ArrayList<AppResultBean.GetDownLoaded>();
                            for (DownloadTask task : tasks) {
                                DownloadExtra extra = DownloadExtra
                                        .parseJObject(task.extra,
                                                DownloadExtra.class);

                                switch (task.info.state) {
                                    case FINISH:
                                        AppResultBean.GetDownLoaded loaded = new AppResultBean.GetDownLoaded();
                                        loaded.appName = task.title;
                                        loaded.apkPath = task.savepath + "/"
                                                + task.filename;
                                        loaded.appId = task.ID;
                                        loaded.iconUrl = extra.iconUrl;
                                        loaded.pkgName = extra.pkgname;

                                        downLoaders.add(loaded);

                                        break;

                                    default:
                                        break;
                                }

                            }
                            AppResultBean<List<AppResultBean.GetDownLoaded>> bean = new AppResultBean<List<AppResultBean.GetDownLoaded>>(json);
                            bean.result = downLoaders;

                            responseToMobile(deBean, cmd, bean.toString());
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                }


        );
//
//        // 报错，没用到先注释
//			/*mCmdHandlerMap
//					.put(SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_GET_TV_INFO
//							.toString(), new CoocaaCmdHandler() {
//						public boolean isSystemApp() {
//							ApplicationInfo appInfo = null;
//							PackageManager pm = mContext.mContext
//									.getPackageManager();
//							try {
//								appInfo = pm.getApplicationInfo(
//										mContext.mContext.getPackageName(), 0);
//							} catch (NameNotFoundException e) {
//
//								e.printStackTrace();
//							}
//							if (appInfo != null && appInfo.uid == 1000)// ((appInfo.flags
//																		// &
//																		// ApplicationInfo.FLAG_SYSTEM)
//																		// !=
//																		// 0))
//								return true;
//							return false;
//						}
//
//						@Override
//						public byte[] onHandle(String cmd, String json) {
//							AppMessage msg = AppMessage.parseJObject(json,
//									AppMessage.class);
//							String channel = CoocaaApplication
//									.getAppChannel(mContext.mContext);
//							MobileTvInfo tvinfo = new MobileTvInfo();
//							tvinfo.channel = channel;
//							tvinfo.mac = CoocaaApplication
//									.getMAC(mContext.mContext);
//							tvinfo.isRoot = isSystemApp();
//							msg.msg = tvinfo.toString();
//							DEChannelSession session = new DEChannelSession(
//									new JsonParams(APP_SESSION, CoocaaDEExtentionDefine.DE_NOTIFY, cmd
//											.toString(), msg.toString()));
//							coocaaApi.writeDEChannel(session);
//							return null;
//						}
//					});*/
//
////			mCmdHandlerMap.put(
////					SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_SPEEDUP
////							.toString(), new CoocaaCmdHandler() {
////						@Override
////						public byte[] onHandle(String cmd, String json) {
////							try {
////								AppMessage msg = AppMessage.parseJObject(json,
////										AppMessage.class);
////								long st = System.currentTimeMillis();
////								boolean ret = ServiceFacotry.getAppService()
////										.speedUp(2000);
////								if (ret) {
////									synchronized (speedUpListener) {
////										speedUpListener.wait();
////									}
////								}
////								long end = System.currentTimeMillis();
////								LogUtils.d("SPEEDUP", " cost:" + (end - st)
////										+ "  ret:" + ret);
////								DEChannelSession session = new DEChannelSession(
////										new JsonParams(APP_SESSION, CoocaaDEExtentionDefine.DE_NOTIFY,
////												cmd, msg.toString()));
////								coocaaApi.writeDEChannel(session);
////							} catch (RemoteException e) {
////
////								e.printStackTrace();
////							} catch (ServiceNotConnectException e) {
////
////								e.printStackTrace();
////							} catch (InterruptedException e) {
////
////								e.printStackTrace();
////							}
////							return null;
////						}
////					});
//
//        // 不再用
////			mCmdHandlerMap
////					.put(SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_MOBILE_UPDATE_APPS_FLAG
////							.toString(), new CoocaaCmdHandler() {
////						@Override
////						public byte[] onHandle(String cmd, String json) {
////							AppMessage msg = AppMessage.parseJObject(json,
////									AppMessage.class);
////							JList<MobileAppInfo> list = JList.parseJObjectList(
////									msg.result, MobileAppInfo.class);
////							for (MobileAppInfo info : list.list)
////								try {
////									ServiceFacotry.getAppService()
////											.updateAppFlag(info.pkgName,
////													info.flag);
////								} catch (RemoteException e) {
////
////									e.printStackTrace();
////								} catch (ServiceNotConnectException e) {
////
////									e.printStackTrace();
////								}
////							return null;
////						}
////					});
//
////			mCmdHandlerMap.put("SKY_COMMAND_APPSTORE_TEST", new CoocaaCmdHandler() {
////
////				@Override
////				public byte[] onHandle(String cmd, String json) {
////					DEChannelSession session = new DEChannelSession(
////							new JsonParams(APP_SESSION, CoocaaDEExtentionDefine.DE_RESPONSE,
////									cmd, json));
////					coocaaApi.writeDEChannel(session);
////					return null;
////				}
////			});
//


    }

    private void notifyToMobile(DETargetBean deBean, String cmd, String params) {
        try {
            DEChannelSession session = new DEChannelSession(
                    new JsonParams(APP_SESSION, CoocaaDEExtentionDefine.DE_NOTIFY,
                            cmd, params));
            if (deBean != null && deBean.ipaddress != null && deBean.port != null && deBean.hostname != null) {
                session.authSession(deBean.ipaddress, deBean.port, deBean.hostname);
                LogUtils.d(TAG, "notifyToMobile   ip:" + session.getAuthIP() + " hostName:" + session.getHostName() + " port:" + session.getAuthPort());
            }
            XServiceManager.getLiteCCConnectorService().writeDEChannel(
                    session.toSerialize());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void responseToMobile(DETargetBean deBean, String cmd, String params) {
        try {
            DEChannelSession session = new DEChannelSession(
                    new JsonParams(APP_SESSION, CoocaaDEExtentionDefine.DE_RESPONSE,
                            cmd, params));
            if (deBean != null && deBean.ipaddress != null && deBean.port != null && deBean.hostname != null) {
                session.authSession(deBean.ipaddress, deBean.port, deBean.hostname);
                LogUtils.d(TAG, "responseToMobile   ip:" + session.getAuthIP() + " hostName:" + session.getHostName() + " port:" + session.getAuthPort());
            }
            XServiceManager.getLiteCCConnectorService().writeDEChannel(
                    session.toSerialize());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private ILiteCCConnectorHandler.Stub ccconnectorHandler = new ILiteCCConnectorHandler.Stub() {
        private byte[] EMPTY = new byte[0];

        @Override
        public byte[] onHandler(String arg0, String arg1, byte[] arg2) throws RemoteException {
            if (arg1.equals(DEDefine.CmdEnum.CMD_READ_BY_DECHANNEL.toString())
                    || arg1.equals(DEDefine.CmdEnum.CMD_WRITE_BY_DECHANNEL.toString())) {
                if (arg2 != null) {
                    DEChannelSession session = DEChannelSession.getDEChannlSession(arg2);
                    LogUtils.v("skydeex", "<<< " + session.getJsonParam().getCmd()
                            + session.getJsonParam().getParam());
                    String json = session.getJsonParam().getParam();
                    CoocaaCmdHandler handler = mCmdHandlerMap.get(session.getJsonParam().getCmd()
                            .toString());
                    if (handler != null) {
                        LogUtils.d(TAG, "onHandler   ip:" + session.getAuthIP() + " hostName:" + session.getHostName() + " port:" + session.getAuthPort());
                        DETargetBean deBean = new DETargetBean(session.getAuthIP(), session.getHostName(), session.getAuthPort());
                        handler.onHandle(deBean, session.getJsonParam().getCmd(), json);
                    }
                } else {
                    LogUtils.d(TAG, "CMD_WRITE_BY_DECHANNEL no received body!!");
                }
            }
            return EMPTY;
        }
    };

    private void runOnThread(Runnable run) {
        AsyncTask.runOnThread(run);
    }

    private AppDetailData getAppDetail(String appid, String version) {
        AppDetailData app = null;
        try {
            // killTimer(TimerType.APP_DETAIL);

            // appdetailTimeoutHandler,appid);
            // startTimer(TimerType.APP_DETAIL,
//				System.out.println(app.title);
            try {
                app = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppDetail(
                        appid, version);

                List<String> infoList = app.infoList;
                for (String info : infoList) {
                    System.out.println(info);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            // killTimer(TimerType.APP_DETAIL);

        } catch (AppStoreException e) {
            LogUtils.d(TAG, "AppStoreException:" + e);
            e.printStackTrace();
        }
        return app;
    }

    private String getDownurl(String appid, String usercount) {
        // return
        // "http://qqime.files2.sogou.com/QQPinyin_android_4.5_1288_1001.apk";
        try {
            String downurl = CoocaaApplication.getCoocaaWebService().getAppStoreService().getDownAddress(
                    Integer.valueOf(appid), usercount);
            System.out.println("download url:" + downurl);
            return downurl;
        } catch (AppStoreException e) {
            e.printStackTrace();
            System.out.println("错误原因：" + e.getErrormsg());
        } catch (NumberFormatException e) {

            e.printStackTrace();
        }
        return null;
    }

    ILitePMInstallListener installListener = new ILitePMInstallListener() {
        @Override
        public void onInstallStart(final String apkfile, final AppInfo appInfo, final InstallParams params) throws RemoteException {
            runOnThread(new Runnable() {
                @Override
                public void run() {
                    AppResultBean<AppResultBean.OnInstallstart> msg = new AppResultBean<AppResultBean.OnInstallstart>();
                    msg.result = new AppResultBean.OnInstallstart(apkfile, appInfo.pkgName);
                    notifyToMobile(null, SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_APPMANAGER_ONINSTALLSTART
                            .toString(), msg.toString());
                }
            });
        }

        @Override
        public void onInstallEnd(final String apkfile, final AppInfo appInfo, int result, final String extra, final InstallParams params) throws RemoteException {
            runOnThread(new Runnable() {
                @Override
                public void run() {
                    if (appInfo == null) {
                        return;
                    }
                    String name = "";
//                            if (success) {
                    PackageManager pm = mContext.getPackageManager();
                    Intent intent = new Intent(Intent.ACTION_MAIN, null);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.setPackage(appInfo.pkgName);
                    List<ResolveInfo> resolveInfo = pm
                            .queryIntentActivities(intent, 0);
                    if (resolveInfo != null && resolveInfo.size() == 1) {
                        ResolveInfo info = resolveInfo.get(0);
                        name = info.loadLabel(
                                mContext.getPackageManager())
                                .toString();
                    }
//                            }
                    AppResultBean<AppResultBean.OnInstalled> msg = new AppResultBean<AppResultBean.OnInstalled>();
                    msg.result = new AppResultBean.OnInstalled(apkfile, appInfo.pkgName, true, extra,
                            name);

                    notifyToMobile(null, SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_APPMANAGER_ONINSTALLED
                            .toString(), msg.toString());
                }
            });
        }

        @Override
        public IBinder asBinder() {
            return null;
        }
    };

    ILitePMUninstallListener uninstallListener = new ILitePMUninstallListener() {
        @Override
        public void onUninstallStart(final AppInfo appInfo) throws RemoteException {
            LogUtils.i("dvlee", "onUninstallStart " + appInfo);

            runOnThread(new Runnable() {
                @Override
                public void run() {
                    AppResultBean<AppResultBean.OnUnInstalled> msg = new AppResultBean<AppResultBean.OnUnInstalled>();
                    AppResultBean.OnUnInstalled r = new AppResultBean.OnUnInstalled(appInfo
                            .pkgName, true, "");
                    msg.result = r;
                    responseToMobile(null, SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_APPMANAGER_ONUNINSTALLSTART
                            .toString(), msg.toString());
                }
            });
        }

        @Override
        public void onUninstallEnd(final AppInfo appInfo, int result, final String extra) throws RemoteException {
            LogUtils.i("dvlee", "onUninstallEnd " + appInfo);

            runOnThread(new Runnable() {
                @Override
                public void run() {
                    AppResultBean<AppResultBean.OnUnInstalled> msg = new AppResultBean<AppResultBean.OnUnInstalled>();
                    msg.result = new AppResultBean.OnUnInstalled(appInfo.pkgName, true, extra);
                    notifyToMobile(null, SkyDEServiceChannelEnum.SKY_COMMAND_APPSTORE_TV_APPMANAGER_ONUNINSTALLED
                            .toString(), msg.toString());
                }
            });
        }

        @Override
        public IBinder asBinder() {
            return null;
        }
    };
}
